package com.rabbitmq.learn.work.unfair;

import com.rabbitmq.client.*;
import com.rabbitmq.learn.common.ConnectionUtils;
import com.rabbitmq.learn.common.RabbitMqConstant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Lxk on 2019/8/11.
 */
@SuppressWarnings("Duplicates")
public class Receiver {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection con = ConnectionUtils.getConnection();

        final Channel channel = con.createChannel();
        //保证一次只分发一条数据
        channel.basicQos(1);

        channel.queueDeclare(RabbitMqConstant.Work.QUEUE_NAME,false,false,false,null);

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body,"utf-8");
                System.out.println("Receiver1: " + msg);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("Receiver1 done!!");
                    //消息手动应答确认
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        //手动应答，消费者处理完成内存中的消息才会被删除，比较安全，不会丢消息，
        // 一旦消费者down，消息会被转发给其它消费者
        boolean autoAck = false;
        channel.basicConsume(RabbitMqConstant.Work.QUEUE_NAME,autoAck,consumer);
    }

}
